package com.zcyr.exception.handler;

import com.zcyr.constant.StatusCode;
import com.zcyr.exception.BadOperationException;
import com.zcyr.exception.CommandExecutorException;
import com.zcyr.exception.DatabaseEnvironmentException;
import com.zcyr.exception.TrymeUserSQLException;
import com.zcyr.util.JsonBody;
import com.zcyr.util.TokenTool;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.HashMap;

/**
 * @author ZCYR
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler
    public JsonBody trymeUserHandler(TrymeUserSQLException e){
        HashMap<String, Object> details = new HashMap<>();
        return JsonBody.custom(StatusCode.SQL_ERROR, e.getMessage()).put("details", details);
    }

    @ExceptionHandler
    public JsonBody badOperationExceptionHandler(BadOperationException e){
        return JsonBody.custom(StatusCode.FAILURE, e.getMessage());
    }

    @ExceptionHandler
    public JsonBody databaseEnvironmentExceptionHandler(DatabaseEnvironmentException e){
        return JsonBody.custom(StatusCode.ENV_ERROR, e.getMessage()).put("token-newEnv", TokenTool.generate("X"));
    }

    @ExceptionHandler
    public JsonBody commandExecutorException(CommandExecutorException e){
        return JsonBody.error(e.getMessage());
    }
}
